/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bytedance.scenedemo.animatiom.sipnner;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.TextField;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.Canvas;
import ohos.agp.utils.Rect;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.multimodalinput.event.TouchEvent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * PopupUtils.
 *
 * @since 2021-06-17
 */
public class PopupUtils {
    private static final int ONE_HUNDRED_SIXTY = 160;

    private PopupUtils() {
    }
    /**
     * 获取屏幕宽度
     *
     * @param context 上下文
     * @return 屏幕宽度
     */
    public static int getWindowWidth(Context context) {
        return context.getResourceManager().getDeviceCapability().width
                * context.getResourceManager().getDeviceCapability().screenDensity / ONE_HUNDRED_SIXTY;
    }

    /**
     * 获取屏幕的高度，包含状态栏，导航栏
     *
     * @param context 上下文
     * @return 屏幕的高度，包含状态栏，导航栏
     */
    public static int getScreenHeight(Context context) {
        return context.getResourceManager().getDeviceCapability().height
                * context.getResourceManager().getDeviceCapability().screenDensity / ONE_HUNDRED_SIXTY;
    }

    /**
     * vp转px
     *
     * @param context 上下文
     * @param vpValue vp
     * @return px
     */
    public static int vp2px(Context context, float vpValue) {
        return (int) (vpValue * context.getResourceManager().getDeviceCapability().screenDensity / ONE_HUNDRED_SIXTY);
    }

    /**
     * 获取状态栏高度，暂无实现，需要开发者传入
     *
     * @param attachPopupView AttachPopupView
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(AttachPopupView attachPopupView) {
        if (attachPopupView != null) {
            return attachPopupView.getStatusBarHeight();
        }
        return 0;
    }

    /**
     * applyPopupSize
     *
     * @param content ComponentContainer
     * @param popupInfo PopupInfo
     * @param afterApplySize int
     */
    public static void applyPopupSize(final ComponentContainer content,
                                      PopupInfo popupInfo,
                                      final Runnable afterApplySize) {
        content.addDrawTask(new Component.DrawTask() {
            @Override
            public void onDraw(Component component, Canvas canvas) {
                ComponentContainer.LayoutConfig params = content.getLayoutConfig();
                Component implView = content.getComponentAt(0);
                ComponentContainer.LayoutConfig implParams = implView.getLayoutConfig();
                int contentWidth = content.getWidth(); // 假设默认Content宽是match，高是wrap
                if (popupInfo.getMaxWidth() > 0) { // response impl view wrap_content params
                    params.width = Math.min(contentWidth, popupInfo.getMaxWidth()); // 指定了最大宽度，就限制最大宽度
                    if (popupInfo.getPopupWidth() > 0) {
                        params.width = Math.min(popupInfo.getPopupWidth(), popupInfo.getMaxWidth());
                        implParams.width = Math.min(popupInfo.getPopupWidth(), popupInfo.getMaxWidth());
                    }
                } else if (popupInfo.getPopupWidth() > 0) {
                    params.width = popupInfo.getPopupWidth();
                    implParams.width = popupInfo.getPopupWidth();
                }

                int contentHeight = content.getHeight();
                if (popupInfo.getMaxHeight() > 0) {
                    params.height = Math.min(contentHeight, popupInfo.getMaxHeight());
                    if (popupInfo.getMaxHeight() > 0) {
                        params.height = Math.min(popupInfo.getPopupHeight(), popupInfo.getMaxHeight());
                        implParams.height = Math.min(popupInfo.getPopupHeight(), popupInfo.getMaxHeight());
                    }
                } else if (popupInfo.getPopupHeight() > 0) {
                    params.height = popupInfo.getPopupHeight();
                    implParams.height = popupInfo.getPopupHeight();
                }
                implView.setLayoutConfig(implParams);
                content.setLayoutConfig(params);

                if (afterApplySize != null) {
                    afterApplySize.run();
                }
            }
        });
    }

    /**
     * isInRect
     *
     * @param xx float
     * @param yy float
     * @param rect Rect
     * @return boolean
     */
    public static boolean isInRect(float xx, float yy, Rect rect) {
        return xx >= rect.left && xx <= rect.right && yy >= rect.top && yy <= rect.bottom;
    }

    /**
     * findAllEditText
     *
     * @param list ArrayList
     * @param group ComponentContainer
     */
    public static void findAllEditText(ArrayList<TextField> list, ComponentContainer group) {
        for (int ii = 0; ii < group.getChildCount(); ii++) {
            Component component = group.getComponentAt(ii);
            if (component instanceof TextField && component.getVisibility() == Component.VISIBLE) {
                list.add((TextField) component);
            } else if (component instanceof ComponentContainer) {
                findAllEditText(list, (ComponentContainer) component);
            }
        }
    }

    /**
     * 获取布局是否是从右到左的布局
     *
     * @param context 上下文
     * @return 布局是否是从右到左的布局
     */
    public static boolean isLayoutRtl(Context context) {
        return false;
    }

    /**
     * 获取圆角背景
     *
     * @param color  背景颜色
     * @param radius 四个角的圆角度数
     * @return 圆角背景
     */
    public static ShapeElement createDrawable(int color, float radius) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(ShapeElement.RECTANGLE);
        drawable.setRgbColor(new RgbColor(color));
        drawable.setCornerRadius(radius);
        return drawable;
    }

    /**
     * 获取屏幕宽度
     *
     * @param context 上下文
     * @return 屏幕宽度，单位px
     */
    public static int getWindowWdith(Context context) {
        return context.getResourceManager().getDeviceCapability().width
                * context.getResourceManager().getDeviceCapability().screenDensity / ONE_HUNDRED_SIXTY;
    }

    /**
     * 获取屏幕高度
     *
     * @param context 上下文
     * @return 屏幕高度，单位px
     */
    public static int getWindowHeight(Context context) {
        return context.getResourceManager().getDeviceCapability().height
                * context.getResourceManager().getDeviceCapability().screenDensity / ONE_HUNDRED_SIXTY;
    }

    /**
     * 通过资源id获取color.json文件中的颜色
     *
     * @param context    上下文
     * @param resColorId 颜色的资源id
     * @return 颜色值
     */
    public static int getColor(Context context, int resColorId) {
        try {
            return context.getResourceManager().getElement(resColorId).getColor();
        } catch (NotExistException | WrongTypeException | IOException e) {
            Logger.getLogger(PopupUtils.class.getName()).log(Level.SEVERE, e.getMessage());
        }
        return 0x000000;
    }

    /**
     * 获取相对于偏移位置的x坐标
     *
     * @param touchEvent 触摸事件
     * @return x坐标
     */
    public static float getX(TouchEvent touchEvent) {
        return touchEvent.getPointerPosition(0).getX();
    }

    /**
     * 获取相对于偏移位置的y坐标
     *
     * @param touchEvent 触摸事件
     * @return y坐标
     */
    public static float getY(TouchEvent touchEvent) {
        return touchEvent.getPointerPosition(0).getY();
    }

    /**
     * 获取相对于屏幕坐标原点的x坐标
     *
     * @param touchEvent 触摸事件
     * @return x坐标
     */
    public static float getRawX(TouchEvent touchEvent) {
        return touchEvent.getPointerScreenPosition(0).getX();
    }

    /**
     * 获取相对于屏幕坐标原点的y坐标
     *
     * @param touchEvent 触摸事件
     * @return y坐标
     */
    public static float getRawY(TouchEvent touchEvent) {
        return touchEvent.getPointerScreenPosition(0).getY();
    }
}
